package com.huangpuweb.api.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * hibernate-validator校验工具类
 *
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 * @author luoxue
 *
 */
public class ValidatorUtils {
	private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
    
    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @return 校验错误原因
     */
    public static String validateEntity(Object object, Class<?>... groups){
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
        	ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            return constraint.getMessage();
        }
        return null;
    }
    
    /**
     * 导入数据校验
     * @param object
     * @param groups
     * @return 校验错误原因
     */
    public static String importValidate(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        return constraintViolations.isEmpty() ? null : constraintViolations.stream()
                .map(ConstraintViolation::getMessage).collect(Collectors.joining("|"));
    }
}
